<template>
  <el-form label-width="120px">
    <el-form-item label="SPU名称"> {{ spu.spuName }} </el-form-item>
    <el-form-item label="SKU名称">
      <el-input placeholder="SKU名称" v-model="skuForm.skuName"></el-input>
    </el-form-item>
    <el-form-item label="价格">
      <el-input
        placeholder="价格"
        type="number"
        v-model="skuForm.price"
      ></el-input>
    </el-form-item>
    <el-form-item label="重量">
      <el-input
        placeholder="重量"
        type="number"
        v-model="skuForm.weight"
      ></el-input>
    </el-form-item>
    <el-form-item label="规格描述">
      <el-input
        placeholder="规格描述"
        type="textarea"
        rows="4"
        v-model="skuForm.skuDesc"
      ></el-input>
    </el-form-item>

    <el-form-item label="平台属性">
      <el-form :inline="true" label-width="100px">
        <el-form-item
          :label="attr.attrName"
          v-for="(attr, index) in attrList"
          :key="attr.id"
        >
          <el-select v-model="attr.attrIdValueId">
            <el-option
              v-for="(attrVal, index) in attr.attrValueList"
              :key="attrVal.id"
              :label="attrVal.valueName"
              :value="`${attr.id}:${attrVal.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="销售属性">
      <el-form :inline="true" label-width="100px">
        <el-form-item
          :label="saleAttr.saleAttrName"
          v-for="(saleAttr, index) in spuSaleAttrList"
          :key="saleAttr.id"
        >
          <el-select v-model="saleAttr.saleAttrIdValueId">
            <el-option
              v-for="(saleAttrValue, index) in saleAttr.spuSaleAttrValueList"
              :key="saleAttrValue.id"
              :label="saleAttrValue.saleAttrValueName"
              :value="`${saleAttr.id}:${saleAttrValue.id}`"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-form-item>
    <el-form-item label="图片列表">
      <el-table
        border
        :data="spuImageList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="图片">
          <template v-slot="{ row }">
            <img :src="row.imgUrl" style="width: 90px; height: 100px" alt="" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-button
              @click="setDefault(row, spuImageList as SpuImageData[])"
              v-if="row.isDefault === '0'"
              type="primary"
              >设为默认</el-button
            >
            <el-tag v-else type="danger">默认</el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="emits('changeState', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import { defineComponent } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
export default defineComponent({
  name: "SkuForm",
});
</script>
<script lang="ts" setup>
import type { SpuData, SpuImageData, SpuSaleAttrData } from "@/api/spu";
import skuApi, {
  type SkuData,
  type SkuImageData,
  type SkuAttrValueData,
  type SkuSaleAttrValueData,
} from "@/api/sku";
import { onMounted, ref } from "vue";
import { useCategoryStore } from "@/stores/category";
import attrApi, { type AttrData } from "@/api/attr";
const props = defineProps<{
  spu: SpuData;
}>();
const emits = defineEmits(["changeState"]);

// 初始化展示数据
const attrList = ref<AttrData[]>([]);
const spuImageList = ref<SpuImageData[]>([]);
const spuSaleAttrList = ref<SpuSaleAttrData[]>([]);
const categoryStore = useCategoryStore();
const { category3Id, category2Id, category1Id } = storeToRefs(categoryStore);
// 请求初始化数据
const getInitAddSkuFormData = async () => {
  const promise1 = attrApi.getList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  const promise2 = skuApi.getSpuImageList(props.spu.id as number);
  const promise3 = skuApi.getSpuSaleAttrList(props.spu.id as number);

  try {
    const res = await Promise.all([promise1, promise2, promise3]);
    attrList.value = res[0];
    // 先默认添加没有默认
    let imgList = res[1];
    imgList.forEach((item) => {
      item.isDefault = "0";
    });
    spuImageList.value = imgList;
    spuSaleAttrList.value = res[2];
  } catch (error) {
    ElMessage.error("获取初始化数据失败");
  }
};

onMounted(() => {
  getInitAddSkuFormData();
});

// 收集数据
const skuForm = ref<SkuData>({
  // v-model直接收集
  price: 0,
  skuName: "",
  skuDesc: "",
  weight: "",
  // 父组件或者仓库可以得到
  spuId: 0,
  tmId: 0,
  category3Id: 0,
  // 需要自己写逻辑收集
  skuDefaultImg: "",
  skuImageList: [],
  skuAttrValueList: [], //平台属性值列表
  skuSaleAttrValueList: [], // 销售属性值列表
});

// 用来手机sku自己的图片列表
const skuImageList = ref<SkuImageData[]>([]);
// 图片选择框的回调
const handleSelectionChange = (val: any) => {
  skuImageList.value = val;
};

// 排他设置图片默认
const setDefault = (row: SpuImageData, spuImageList: SpuImageData[]) => {
  // 先让所有的图片都为零
  spuImageList.forEach((item) => (item.isDefault = "0"));
  // 当前为选中
  row.isDefault = "1";
  // 收集默认图片
  skuForm.value.skuDefaultImg = row.imgUrl as string;
};

// 保存操作
const save = async () => {
  let sku = skuForm.value;
  // 把sku当中从父组件和仓库拿到的数据整理到位
  sku.category3Id = category3Id.value as number;
  sku.spuId = props.spu.id as number;
  sku.tmId = props.spu.tmId as number;
  // 整理sku的图片列表
  sku.skuImageList = skuImageList.value.map((item) => {
    return {
      imgName: item.imgName,
      imgUrl: item.imgUrl,
      spuImgId: item.id as number,
      isDefault: item.isDefault,
    };
  });

  // 整理sku的平台属性值列表
  sku.skuAttrValueList = attrList.value.reduce<SkuAttrValueData[]>(
    (prev, item) => {
      if (item.attrIdValueId) {
        let [attrId, valueId] = item.attrIdValueId.split(":");
        let obj = { attrId, valueId };
        prev.push(obj);
      }
      return prev;
    },
    []
  );

  // 整理销售属性值列表
  sku.skuSaleAttrValueList = spuSaleAttrList.value.reduce<
    SkuSaleAttrValueData[]
  >((prev, item) => {
    if (item.saleAttrIdValueId) {
      let [saleAttrId, saleAttrValueId] = item.saleAttrIdValueId.split(":");
      let obj = { saleAttrId, saleAttrValueId };
      prev.push(obj);
    }
    return prev;
  }, []);

  // 发送请求
  try {
    await skuApi.saveSkuInfo(sku);
    ElMessage.success("保存成功");
    emits("changeState", 1);
  } catch (error) {
    ElMessage.error("保存失败");
  }
};
</script>

<style lang="less" scoped></style>
